<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
    
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="../plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="../plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="../plugins/kindeditor/lang/zh_CN.js"></script>

	<!--bootstrap-toastr-->
	<script type="text/javascript" src="/bootstrap/toastr/toastr.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/bootstrap/toastr/toastr.css">

	<!--bootStrap-fileinput-->
	<script type="text/javascript" src="/bootstrap/bootstrap-fileinput/js/fileinput.min.js"></script>
	<script type="text/javascript" src="/bootstrap/bootstrap-fileinput/js/locales/zh.js"></script>
	<link rel="stylesheet" type="text/css" href="/bootstrap/bootstrap-fileinput/css/fileinput.min.css">
	<script>

		$(function () {
			$('#uploadImg').fileinput({
				language: 'zh',
				uploadUrl: "/oss/upload",
				browseClass: 'btn btn-primary',
				maxFileCount: 1,//最多支持上传的个数
				enctype: 'multipart/form-data',
				maxFileSize: 1024, //单位为kb, 如果为0表示不限制文件大小
				allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
				initialPreviewAsData: true, // 是否初始化预览图片
				initialPreviewFileType: 'image', //回显文件的类型(初始化预览图片类型)
			});

			$("#uploadImg").on("fileuploaded", function(event, data, previewId, index){
				if(data.response.code == 200){
					$("#goodImg").val(data.response.data);
				}
			});
		});

		$(function () {
			$.ajax({
				url : "/goods/getItemCatSort",
				type : "post",
				dataType : "json",
				success : function (returnData) {
					var data = returnData.data;
					if (returnData.code == 200) {
						for (var i = 0; i < data.length; i++){
							$("#c1id").append("<option value='"+ data[i].id +"'>"+ data[i].name +"</option>");
						}
					} else {
						toastr.error(data.message);
					}
				},
				error : function (returnData) {
					toastr.error(returnData.message);
				}
			});
		});
		
		function itemCatChange1() {
			//清空上次选择的信息
			$("#c2id option:gt(0)").remove();
			$("#c3id option:gt(0)").remove();

			var parentId = $("#c1id option:selected").val();
			if (parentId == -1){
				$("#typeTemplateId").text("");
				return;
			}
			$.ajax({
				url : "/goods/getItemCatSort",
				type : "post",
				data : {parentId : parentId},
				dataType : "json",
				success : function (returnData) {
					var data = returnData.data;
					if (returnData.code == 200) {
						for (var i = 0; i < data.length; i++){
							$("#c2id").append("<option value='"+ data[i].id +"'>"+ data[i].name +"</option>");
						}
					} else {
						toastr.error(returnData.message);
					}
				},
				error : function () {
					toastr.error("系统错误");
				}
			});
		}

		function itemCatChange2() {
			//清空上次选择的信息
			$("#c3id option:gt(0)").remove();

			var parentId = $("#c2id option:selected").val();
			if (parentId == -1){
				$("#typeTemplateId").text("");
				return;
			}
			$.ajax({
				url : "/goods/getItemCatSort",
				type : "post",
				data : {parentId : parentId},
				dataType : "json",
				success : function (returnData) {
					var data = returnData.data;
					if (returnData.code == 200) {
						for (var i = 0; i < data.length; i++){
							$("#c3id").append("<option value='"+ data[i].id +"'>"+ data[i].name +"</option>");
						}
					} else {
						toastr.error(returnData.message);
					}
				},
				error : function () {
					toastr.error("系统错误");
				}
			});
		}

		function itemCatChange3() {
			//获取第三级id给模板ID赋值
			var parentId = $("#c3id option:selected").val();
			if (parentId == -1){
				$("#typeTemplateId").text("");
			}else {
				$("#typeTemplateId").text(parentId);
			}

			$.ajax({
				url : "/goods/getTemplateByItemCatId",
				type : "post",
				data : {id : parentId},
				dataType : "json",
				success : function (returnData) {
					if (returnData.code == 200) {
						// 通过模板表中的关联品牌字段  构建品牌下拉框
						var brands = returnData.data.brandIds;
						var brandsJson = JSON.parse(brands);
						var brandSelectHtml = "";
						$(brandsJson).each(function (i, e) {
							brandSelectHtml += "<option value='" + e.id + "'>" + e.text + "</option>";
						});
						$("#brandId").html(brandSelectHtml);

						// 该商品类型模板拓展属性
						var customItemsJson = JSON.parse(returnData.data.customAttributeItems);
						var customItem = "";
						$(customItemsJson).each(function (i, e) {
							customItem += "<div>";
							customItem += "<div class='col-md-2 title'>" + e.text + "</div>";
							customItem += "<div class='col-md-10 data'>";
							customItem += "<input class='form-control' placeholder='请输入" + e.text + "拓展属性'>";
							customItem += "</div>";
							customItem += "</div>";
						});
						$("#itemCate").html(customItem);
					} else {
						toastr.error(returnData.message);
					}

				},
				error : function (returnData) {
					toastr.error("系统错误");
				}
			});
		}

		function selectSpec() {
			//获取第三级id给模板ID赋值
			var parentId = $("#c3id option:selected").val();
			if (parentId == -1){
				return;
			}else {
					$.ajax({
						url: "/goods/getSpecsAndOptionsByItemCatId",
						type: "post",
						data: {itemCatId: parentId},
						dataType: "json",
						success: function (returnData) {
							if (returnData.code == 200) {
								var speOp = returnData.data;
								var html = '';
								if ($("#checkId").is(":checked")) {
									$.each(speOp, function (i, e) {
										html += '<div><div class="col-md-2 title">' + e.text + '</div>'
										html += '<div class="col-md-10 data">';
										$.each(e.options, function (index, el) {
											html += '<span>'
											html += '<input  onclick="checkSpec(this,\'' + e.text + '\',\'' + el.optionName + '\')" type="checkbox" value="' + el.id + '" >' + el.optionName + '</span>'

										})
										html += '</div></div>'
									});
								}
								$("#optionsType").html(html)
							} else {
								toastr.error("规格查询失败");
							}
						},
						error: function () {
							toastr.error("系统错误");
						}
					});
			}
		}

		var items = [];
		//勾选规格选项复选框函数
		function checkSpec(event,name,value){
			//调用方法判断原集合中是否已有attributeName
			var obj = searchObjectByKey(items,'attributeName',name);
			if(obj != null){
				if($(event).prop('checked')){//勾选
					//如果之前有数据，往原有的对象中追加
					obj.attributeValue.push(value);
				}else{//取消勾选
					obj.attributeValue.splice(obj.attributeValue.indexOf(value),1);//从items中移除规格选项
					//如果规格选项没有数据了
					if(obj.attributeValue.length==0){
						//移除items中的数据
						items.splice(items.indexOf(obj),1)
					}
				}
			}else{
				//如果之前没有数据，items新加数据
				items.push({'attributeName':name,'attributeValue':[value]});
			}
			// 打印items数据
			// $("#specDiv2").html(JSON.stringify(items));

			// 构建勾选的规格数据
			createItemList(event);
		}

		//遍历组装用户勾选规格选项数据
		function searchObjectByKey(list,attributeName,attributeValue){
			for(var i=0;i<list.length;i++){
				//如果list中我们选择key存在
				if(list[i][attributeName] == attributeValue){
					return list[i];//返回当前对象
				}
			}
			//遍历结束后都不存在，返回null
			return null;
		}

		//创建SKU列表
		var itemList = null;
		function createItemList(event){
			var itemList2 = [{spec:{}}] ;
			for(var i = 0; i < items.length; i++){
				itemList2 =  addColum(itemList2,items[i].attributeName,items[i].attributeValue);
			}
			itemList = itemList2;
			// // 打印保存itemList数据
			// $("#itemTableDiv2").html(JSON.stringify(itemList));

			// 构建table
			var table = "";
			table += '<thead>'
			table += '<tr>'
			for (var f = 0; f < items.length; f++) {
				table += '<th class="sorting">' + items[f].attributeName + '</th>'
			}

			table += '<th class="sorting">价格</th>'
			table += '<th class="sorting">库存</th>'
			table += '<th class="sorting">是否启用</th>'
			table += '<th class="sorting">是否默认</th>'
			table += '</tr>'
			table += '</thead>'
			table += '<tbody id="specOptionTbody">'
			for (var j = 0; j < itemList.length; j++) {
				table += '<tr>'
				for (var e = 0; e < items.length; e++) {
					table += '<td>' + itemList[j].spec[items[e].attributeName] + '</td>'

				}
				table += '<td>'
				table += '<input class="form-control"  placeholder="价格"></td>'
				table += '<td><input class="form-control" placeholder="库存数量"></td>'
				table += '<td><input type="checkbox" ></td>'
				table += '<td> <input type="checkbox" value="1"></td>'
				table += '</tr>'
			}

			table += '</tbody>'

			$("#itemTables").html(table)
			// console.log("测试"+JSON.stringify(itemList))
		}

		//添加表格的列
		function addColum(list,columName,columValues) {
			//定义新集合接收行
			var newList = [];
			for(var i = 0; i < list.length; i++){
				var oldRow = list[i];
				for(var j=0; j < columValues.length; j++){
					var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
					newRow.spec[columName] = columValues[j];
					newList.push(newRow)
				}
			}
			return newList;
		}


		//增加商品图片
		function insertGoodsImage() {
			var goodImgColor = $("#goodImgColor").val();
			var goodImg = $("#goodImg").val();

			// 拼接在页面上
			var goodsImages = "<tr>";
			goodsImages += "<td>" + goodImgColor + "</td>";
			goodsImages += "<td><img alt='' src='" + goodImg +" ' width='100px' height='100px'></td>";
			goodsImages += "<td><button type='button' class='btn btn-default' title='删除' onclick='deleteGoodsImage(this)' ><i class='fa fa-trash-o'></i> 删除</button></td>";
			goodsImages += "</tr>";
			$("#goodImages").append(goodsImages);

			// 清空图片弹出窗口
			$("#uploadModal input").val("");
		}

		// 删除图片编辑中的tr
		function deleteGoodsImage(o) {
			// 获取button的tr
			var tr = o.parentNode.parentNode;
			// 获取这个tr的tbody
			var tbody = tr.parentNode;
			// 删除这个button所在的tr
			tbody.removeChild(tr);
		}

		//添加商品
		function insertGoods() {

			var parentId = $("#c3id option:selected").val();

			//商品图片
			var goodsImageList = [];
			var trs = $("#goodImages tr");
			for (var i = 0; i < trs.length; i++) {
				var tds = $(trs[i]).find("td"); // 获取td
				var color = $(tds[0]).text(); // 获取第一个td下text
				var url = $(tds[1]).find("img").prop("src"); // 获取第一个td下text
				if (color != '' && color != null) {
					goodsImageList.push({color:color, url:url});
				}
			}

			//goods_desc表中的image
			var itemImagesListJsonStr = JSON.stringify(goodsImageList);
			// goods表中的小图
			var firstImgTd = $(trs[0]).find("td"); // 获取第一个tr下的td
			var firstImgUrl = $(firstImgTd[1]).find("img").prop("src");// 获取第二个td下的src


			// 拓展属性
			var customAttributeItems = [];
			var divs = $("#itemCate").children(); // 获取这个div下的所有div子标签
			for (var i = 0; i < divs.length; i++) {
				var childrenDiv = $(divs[i]).find("div"); // 获取div[i]下的div
				var text = $(childrenDiv[0]).text(); // 获取第一个div的text
				var value = $(childrenDiv[1]).find("input").val(); // 获取第二个div下input的值
				customAttributeItems.push({text:text, value:value});
			}
			var customAttributeItemsJsonStr = JSON.stringify(customAttributeItems);

			// 规格页选中的规格数据
			var specificationItemsJsonStr = JSON.stringify(items);
			//拼接tb_item
			var tb_items = [];
			//获取价格 库存
			var trs = $("#specOptionTbody").find("tr");
			var goodsName = $("#goodsName").val();
			for (var j = 0; j < itemList.length; j++) {
				var title = '';
				for (var k = 0; k < items.length; k++) {
					title += goodsName+" "+items[k].attributeName+""+itemList[j].spec[items[k].attributeName]+" "
				}
				var tds = $(trs[j]).find("td");
				var price = $(tds[items.length]).find("input").val()
				var num = $(tds[items.length + 1]).find("input").val()
				var isDefault = $(tds[items.length + 3]).find("input").val()
				var item = {"title":title,"spec":JSON.stringify(itemList[j].spec),"sellPoint":$("#caption").val(),"price":price,"stockCount":num,"num":num,"image":goodsImageList[0].url,"isDefault":isDefault};
				tb_items.push(item)
			}

			var tbItemsJson = JSON.stringify(tb_items)
			console.log(tb_items)

			var goods = $("#insertGoodsForm").serialize() + "&customAttributeItems=" + customAttributeItemsJsonStr
					+ "&itemImages=" + itemImagesListJsonStr + "&smallPic=" + firstImgUrl + "&itemStr=" + tbItemsJson
					+ "&specificationItems=" + specificationItemsJsonStr + "&parentId=" + parentId ;
			// console.log(itemListJson)
			// console.log(specificationItemsJsonStr)

			$.ajax({
				url : "/goods/insertGoods",
				type : "post",
				data : goods,
				dataType : "json",
				success : function (returnData) {
					if (returnData.code == 200) {
						toastr.success(returnData.message);
					} else {
						toastr.error(returnData.message);
					}
					setTimeout(function () {
						reload();
					}, 1000);
				},
				error : function () {
					toastr.error("系统错误");
				}
			});
		}
		function reload() {
			window.location.reload();
		}

	</script>

</head>

<body class="hold-transition skin-red sidebar-mini" >

	<form id="insertGoodsForm">
            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
		                          
		                           	  <div class="col-md-10 data">
		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" name="category1Id" id="c1id" onchange="itemCatChange1()">
														<option value="-1">--请选择--</option>
													</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" name="category2Id" id="c2id" onchange="itemCatChange2()">
														<option value="-1">--请选择--</option>
													</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" name="category3Id" id="c3id" onchange="itemCatChange3()">
														<option value="-1">--请选择--</option>
													</select>
		                              			</td>
		                              			<td>
		                           	  				模板ID:<span  id="typeTemplateId" name="typeTemplateId"></span>
		                              			</td>
		                           	  		</tr>
		                           	  	</table>
		                              	
		                              </div>	                              
		                          	  
									
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" id="goodsName" name="goodsName" class="form-control"    placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select id="brandId" name="brandId" class="form-control" >
									  </select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" name="caption" id="caption" class="form-control"   placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" name="price" class="form-control"  placeholder="价格" value="">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea id="introduction" name="introduction" style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4" id="packageList" name="packageList"  class="form-control"   placeholder="包装列表"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4" id="saleService" name="saleService"  class="form-control"    placeholder="售后服务"></textarea>
		                           </div>                        
                                  
                                    
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="goodImages">
					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
                                <div class="row data-type" id="itemCate">

                                </div>
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input id="checkId" type="checkbox" onclick="selectSpec()">
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div id="optionsType" class="row data-type"></div>
	
	                                
	                                <div  class="row data-type">
										<table class="table table-bordered table-striped table-hover dataTable" id="itemTables"></table>
									</div>
	                                
	                            </div>
                            </div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="insertGoods()"><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
			</form>
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" id="goodImgColor" placeholder="颜色" >  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
									<label for="uploadImg">商品图片预览</label>
									<input type="file" multiple class="form-control" id="uploadImg" name="myFile">
									<input type="hidden" class="form-control" id="goodImg" name="goodImg" readonly="readonly">
								</td>
							</tr>
						</table>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<button class="btn btn-success"  data-dismiss="modal" onclick="insertGoodsImage()"  aria-hidden="true">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="introduction"]', {
			allowFileManager : true,
			// 同步kindEditor的值到textarea文本库
			afterBlur: function(){this.sync();}
		});
	});

</script>
       
</body>

</html>